﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Pixysoft.Framework.Reflection.Controller
{
    class DynamicCacheFactory<I, T>
    {
        private static readonly ReaderWriterLock locker = new ReaderWriterLock();

        Dictionary<I, T> caches = new Dictionary<I, T>();

        private static volatile DynamicCacheFactory<I, T> instance;

        private static object syncRoot = new Object();

        public static DynamicCacheFactory<I, T> Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new DynamicCacheFactory<I, T>();
                        }
                    }
                }
                return instance;
            }
        }

        public void ReadLock()
        {
            locker.AcquireReaderLock(Timeout.Infinite);
        }

        public void ReadUnlock()
        {
            locker.ReleaseReaderLock();
        }

        public void WriteLock()
        {
            locker.AcquireWriterLock(Timeout.Infinite);
        }

        public void WriteUnlock()
        {
            locker.ReleaseWriterLock();
        }

        public bool Contains(I key)
        {
            return caches.ContainsKey(key);
        }

        public T GetValue(I key)
        {
            //不判断 从1,621ms => 1,599ms

            //if (!caches.ContainsKey(key))
            //    return default(T);

            return caches[key];
        }

        public void AddValue(I key, T value)
        {
            caches.Add(key, value);
        }

        public void ClearAll()
        {
            caches.Clear();
        }

    }

}
